package com.cade.agriculturemall.base;

import android.support.annotation.IdRes;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.util.SparseArray;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

/**
 * Created by tom on 17/7/28.
 */

public class FWViewHolder extends ViewHolder implements View.OnClickListener, View.OnLongClickListener{
    protected SparseArray<View> mViews = null;
    private OnViewHolderClickListener mOnViewHolderClickListener;

    public FWViewHolder(View itemView) {
        super(itemView);
        this.mViews = new SparseArray();
        itemView.setOnClickListener(this);
        itemView.setOnLongClickListener(this);
    }

    public  <T extends View> T findViewById(@IdRes int id) {
        View view = this.mViews.get(id);
        if (view == null) {
            view = this.itemView.findViewById(id);
            mViews.put(id, view);
        }

        return (T) view;
    }

    public void setText(@IdRes int id, CharSequence text) {
        TextView textView = this.findViewById(id);
        if (textView != null) {
            textView.setText(text);
        }

    }

    public void setOnClick(@IdRes int id, View.OnClickListener onClickListener) {
        this.findViewById(id).setOnClickListener(onClickListener);
    }

    public void setChecked(@IdRes int id, boolean checked) {
        ((CheckBox) this.findViewById(id)).setChecked(checked);
    }

    public void showOrHide(@IdRes int id, boolean show) {
        if (this.findViewById(id) != null)
            this.findViewById(id).setVisibility(show ? View.VISIBLE : View.GONE);
    }

    public void setOnViewHolderClickListener(OnViewHolderClickListener onViewHolderClickListener) {
        mOnViewHolderClickListener = onViewHolderClickListener;
    }

    @Override
    public void onClick(View v) {
        if (mOnViewHolderClickListener != null){
            mOnViewHolderClickListener.onItemClick(v, getAdapterPosition());
        }
    }

    @Override
    public boolean onLongClick(View v) {
        if (mOnViewHolderClickListener != null){
            mOnViewHolderClickListener.onItemLongClick(v, getAdapterPosition());
        }
        return false;
    }

    public interface OnViewHolderClickListener{
        void onItemClick(View view, int position);
        void onItemLongClick(View view, int position);
    }
}
